//
//  GMStudyVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/10/16.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMStudyVC.h"
#import "GMHomeImgCell.h"
#import "GMHomeTableViewCell.h"
#import "GMStudyResModel.h"
#import "GMBuyVideoVC.h"
#import "GMPlayerViewController.h"
#import "GMReadPDFVC.h"
#import "GMCoursePackageVC.h"
#import "GMExercisesVC.h"
#import "GMExaminationVC.h"
#import "GMBuyFile.h"
#import "GMBaseNavigationController.h"
@interface GMStudyVC ()<UITableViewDataSource,UITableViewDelegate,PYSearchViewControllerDelegate>
@property (nonatomic, strong) UITableView *tabView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSMutableArray *dataArr;
@end

@implementation GMStudyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    self.page = 0;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getData:) name:@"postStudyRes" object:nil];
    self.title = @"搜索结果";
    if (!kIsEmptyString(self.searchText)) {
        [self addRightBarButtonWithFirstImage:[UIImage imageNamed:@"search-white-64"] action:@selector(searchBtnClick)];
        [self getNewStudyData];
    }
}
-(void)searchBtnClick{
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:nil searchBarPlaceholder:@"请输入商品名称进行搜索" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        self.searchText = searchText;
        [self dismissViewControllerAnimated:YES completion:^{
             [self getNewStudyData];
        }];
    }];
    searchViewController.searchTextField.textColor = [UIColor colorWithHexString:@"101010" andAlpha:1.0];
    searchViewController.searchTextField.tintColor = [UIColor colorWithHexString:@"101010" andAlpha:1.0];
    searchViewController.searchTextField.font = [UIFont systemFontOfSize:10.0f];
    searchViewController.searchBar.layer.cornerRadius = 16;
    searchViewController.searchBar.clipsToBounds = YES;
    searchViewController.searchBar.layer.borderWidth = 0.5;
    searchViewController.searchBar.layer.borderColor = [UIColor colorWithHexString:@"D7D7D7" andAlpha:1.0].CGColor;
    [searchViewController.cancelButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
    searchViewController.cancelButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    
    searchViewController.delegate = self;
    searchViewController.hotSearchStyle = PYHotSearchStyleDefault;
    searchViewController.searchHistoryStyle = PYSearchHistoryStyleARCBorderTag;
    GMBaseNavigationController *base = [[GMBaseNavigationController alloc]initWithRootViewController:searchViewController];
    [self presentViewController:base animated:YES completion:nil];
}
-(void)getData:(NSNotification *)noti{
    NSArray *arr = [GMStudyResModel mj_objectArrayWithKeyValuesArray:[noti object]];
    [self.dataArr removeAllObjects];
    [self.dataArr addObjectsFromArray:arr];
    [self.tabView reloadData];
}
-(void)getNewStudyData{
    self.page =0;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"pageIndex":@(self.page),
                          @"key":self.searchText?self.searchText:@""
                          };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetStudyRes&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [self.tabView.mj_footer endRefreshing];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *arr = [GMStudyResModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [self.dataArr removeAllObjects];
                [self.dataArr addObjectsFromArray:arr];
                [self.tabView reloadData];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"请求出错" toView:self.view];
        }
    }];
}
-(void)getMoreStudyData{
    self.page ++;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"pageIndex":@(self.page),
                          @"key":self.searchText?self.searchText:@""
                          };
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetStudyRes&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *arr = [GMStudyResModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [self.dataArr addObjectsFromArray:arr];
                if (arr.count > 0) {
                    [self.tabView.mj_footer endRefreshing];
                    [self.tabView reloadData];
                }else{
                    self.tabView.mj_footer.state = MJRefreshStateNoMoreData;
                }
                
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"请求出错" toView:self.view];
        }
    }];
}
-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}
-(UITableView *)tabView{
    if (!_tabView) {
        _tabView = [UITableView zj_tableViewWithSuperview:self.view delegate:self style:UITableViewStylePlain constraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        _tabView.separatorStyle =UITableViewCellSeparatorStyleNone;
        [_tabView registerNib:[UINib nibWithNibName:@"GMHomeImgCell" bundle:nil] forCellReuseIdentifier:@"GMHomeImgCell"];
        [_tabView registerNib:[UINib nibWithNibName:@"GMHomeTableViewCell" bundle:nil] forCellReuseIdentifier:@"GMHomeTableViewCell"];
        _tabView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreStudyData)];
    }
    return _tabView;
}
#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GMStudyResModel *stuModel = self.dataArr[indexPath.row];
    if (stuModel.IsAd) {
        GMHomeImgCell *imgCell = [tableView dequeueReusableCellWithIdentifier:@"GMHomeImgCell" forIndexPath:indexPath];
        imgCell.stuModel = stuModel;
        return imgCell;
    }else{
        GMHomeTableViewCell *stuCell = [tableView dequeueReusableCellWithIdentifier:@"GMHomeTableViewCell" forIndexPath:indexPath];
        stuCell.stuModel = stuModel;
        return stuCell;
    }
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     return 80;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GMStudyResModel *model = self.dataArr[indexPath.row];
    if (model.IsAd) {//广告 就更新阅读计数
        [self updateReadCount:model.Id];
    }
    if (model.NormalCode >0) {
        if (model.NormalCode ==1) {
            [MBProgressHUD showErrorOrSuc:@"关联资源已下架或不可用" toView:self.view];
        }else if (model.NormalCode ==2){
            [MBProgressHUD showErrorOrSuc:@"当前手机型 号非购买资源所用手机型号，你可以到“我的 - 主页 - 个人资料(付费资源管理)”模块申请变更手机型号。" toView:self.view];
        }else if (model.NormalCode ==3){
            [MBProgressHUD showErrorOrSuc:@"本期培训已结束，课件自动关闭；若有需要请报名参加下期培训。" toView:self.view];
        }
       
    }else{
        if ([model.ResType isEqualToNumber:@(1)]) {
            /**视频*/
            if (model.IsFree) {
                GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
                play.resId = model.Id;
                [self.navigationController pushViewController:play animated:YES];
            }else{
                GMBuyVideoVC *vc = [[GMBuyVideoVC alloc] init];
                vc.resId = model.Id;
                vc.ResType = model.ResType;
              
                [self.navigationController pushViewController:vc animated:YES];
            }

        }else if ([model.ResType isEqualToNumber:@(2)]){
            /**文档*/
            if (model.IsFree) {
                GMReadPDFVC *file = [[GMReadPDFVC alloc] init];
                file.resId = model.Id;
                [self.navigationController pushViewController:file animated:YES];
            }else{
                GMBuyFile *file = [[GMBuyFile alloc] init];
              
                file.resId = model.Id;
                 file.ResType = model.ResType;
                [self.navigationController pushViewController:file animated:YES];
            }
           
        }else if ([model.ResType isEqualToNumber:@(3)]){
            /**习题*/
            if (model.IsFree) {
                GMExercisesVC *exercises =[[GMExercisesVC alloc] init];
                exercises.resId = model.Id;
                [self.navigationController pushViewController:exercises animated:YES];
            }else{
                GMBuyFile *file = [[GMBuyFile alloc] init];
              
                file.resId = model.Id;
                 file.ResType = model.ResType;
                [self.navigationController pushViewController:file animated:YES];
            }
           
        }else if ([model.ResType isEqualToNumber:@(4)]){
            /**试卷*/
            if (model.IsFree) {
                GMExaminationVC *exam = [[GMExaminationVC alloc] init];
                exam.resId = model.Id;
                [self.navigationController pushViewController:exam animated:YES];
            }else{
                GMBuyFile *file = [[GMBuyFile alloc] init];
              
                file.resId = model.Id;
                file.ResType = model.ResType;
                [self.navigationController pushViewController:file animated:YES];
            }
          
        }else if ([model.ResType isEqualToNumber:@(9)]){
            /**课程包*/

            if (model.IsFree) {
                GMCoursePackageVC *package = [[GMCoursePackageVC alloc] init];
                package.resId = model.Id;
                package.titleStr = model.Name;
                [self.navigationController pushViewController:package animated:YES];
            }else{
                GMBuyFile *file = [[GMBuyFile alloc] init];
               
                file.resId = model.Id;
                file.ResType = model.ResType;
                [self.navigationController pushViewController:file animated:YES];
            }
        }
    }
    
}

/*
 *更新广告阅读计数
 */
-(void)updateReadCount:(NSString *)addId{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    //广告Id
    [dict setValue:addId forKey:@"adId"];
    
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UpdateAdCount&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                XZLog(@"计数成功");
            }else{
                XZLog(@"计数失败");
            }
            
        }else{
            XZLog(@"%@",error);
        }
    }];
}
@end
